<template>
  <div>
    <div class="h12" />
    <el-card>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="设备控制" name="first">
          <div class="action-container">
            <el-row>
              <div v-for="(item, index) in rtuActionDisplays" :key="index">
                <el-col
                  v-if="item.action_type == 'select'"
                  :span="6"
                  style="margin: 8px 0"
                >
                  <div class="action-board">
                    <b>{{ item.name }}：</b>
                    <el-button-group>
                      <el-button
                        v-for="(citem, cindex) in item.action_arr"
                        :key="cindex"
                        :type="getButtonType(item, cindex)"
                        @click="
                          citem.params === 'fkq'
                            ? openFkqModal(item)
                            : sendCommand(citem, item)
                        "
                      >
                        {{ citem.name }}
                      </el-button>
                    </el-button-group>
                  </div>
                </el-col>
                <el-col
                  v-if="item.action_type == 'raw'"
                  :span="12"
                  style="display: flex; align-items: center; margin: 6px 0"
                >
                  <b style="width: 100px; text-align: right">
                    {{ item.name }}：
                  </b>
                  <span style="width: 100%; margin-left: auto">
                    <el-slider
                      v-model="item.default_val"
                      show-input
                      @change="changeSlider(item)"
                    />
                  </span>
                </el-col>
                <el-col
                  v-if="item.action_type == 'input'"
                  :span="24"
                  style="display: flex; align-items: center; margin: 6px 0"
                >
                  <span style="width: 100px">{{ item.name }}：</span>
                  <span style="width: 100%; margin-left: auto">
                    <el-slider
                      v-model="sliderValue"
                      show-input
                      @change="changeSlider(item)"
                    />
                  </span>
                </el-col>
              </div>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作履历" name="second">
          <template slot="label">
            <div class="d-flex align-items-center">
              <span>操作履历</span>
              <div v-if="activeName === 'second'">
                <i
                  class="el-icon-refresh ml12 mr12 font18"
                  @click.stop="refresh"
                />
                <!-- <el-switch v-model="autoRefresh" inactive-text="不自动刷新" active-text="自动刷新" :inactive-value="0" :active-value="1"></el-switch> -->
              </div>
            </div>
          </template>
          <el-empty v-if="actionDays.length === 0" description="暂无记录" />
          <el-tabs v-else :tab-position="tabPosition" @tab-click="handleClick">
            <el-tab-pane
              v-for="(item, index) in actionDays"
              :key="index"
              v-loading="loading"
              :label="item"
            >
              <div class="h12" />
              <el-radio-group v-model="reverse" style="margin-left: 40px">
                <el-radio :label="true">倒序</el-radio>
                <el-radio :label="false">正序</el-radio>
              </el-radio-group>
              <div class="h12" />
              <div
                style="
                  max-height: 500px;
                  padding: 10px 0 24px 0;
                  overflow-y: scroll;
                "
              >
                <el-timeline :reverse="reverse">
                  <el-timeline-item
                    v-for="(citem, cindex) in actions"
                    :key="cindex"
                    placement="top"
                    :timestamp="citem.time"
                  >
                    <div>
                      <div class="h12" />
                      <div>
                        <span class="mr12">{{ citem.name }}</span>
                        <b :class="getClass(citem.action)">
                          {{ citem.action }}
                        </b>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="上报统计" name="fourth">
          <div class="tip d-flex" style="padding: 12px">
            <el-date-picker
              v-model="searchForm.timetran"
              class="mr12"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
            <el-select
              v-model="searchForm.namekey"
              class="mr12"
              clearable
              filterable
              placeholder="属性"
            >
              <el-option
                v-for="(item, index) in rtuPortDisplays"
                :key="index"
                :label="item.name"
                :value="item.namekey"
              />
            </el-select>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="default" @click="reset">重置</el-button>
            <b
              v-if="censusCount !== ''"
              class="font16 color-danger mlauto"
              style="line-height: 32px"
            >
              上报总次数：{{ censusCount }}
            </b>
          </div>
          <div class="h12" />
          <el-empty v-if="censusData.length === 0" description="暂无任何记录" />
          <el-table
            v-else
            border
            :data="censusData"
            height="400"
            style="width: 100%"
          >
            <el-table-column
              align="center"
              label="起始时间"
              prop="time_start"
              width="240"
            />
            <el-table-column
              align="center"
              label="结束时间"
              prop="time_end"
              width="240"
            />
            <el-table-column
              align="center"
              label="上报次数"
              prop="val"
              width="240"
            />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      v-drag
      :append-to-body="true"
      destroy-on-close
      title="喷头控制"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <div class="tags">
        <el-tag
          v-for="(item, index) in formData.valves"
          :key="index"
          closable
          style="margin: 8px 8px 8px 0"
          type="primary"
          @close="closeTag(index)"
        >
          {{ item.name }}
        </el-tag>
      </div>
      <div class="h20" />
      <el-form
        ref="form"
        label-suffix="："
        label-width="100px"
        :model="formData"
        :rules="rules"
      >
        <el-form-item label="启闭设定" prop="cycle">
          <el-radio-group v-model="actionType" @change="changeActionType">
            <el-radio :label="1">打开</el-radio>
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="2">占空比</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="脉冲周期" prop="cycle">
              <el-input v-model="formData.cycle" placeholder="脉冲周期">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="占空比" prop="PWM">
              <el-input v-model="formData.PWM" placeholder="占空比">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            icon="el-icon-check"
            type="primary"
            @click="pwmValve('form')"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {
    sendPWM,
    sendCommand,
    getActions,
    getActionDays,
    census as getAll,
  } from '@/api/device'
  import { sum } from '@/utils'
  export default {
    data() {
      return {
        topic: '',
        activeCName: 'first',
        activeNames: ['1'],
        dialogVisible: false,
        childSelected: [],
        formData: {
          cycle: 60,
          PWM: 60,
          type: 'valves',
          valves: [],
        },
        actionType: 2,
        rules: {
          cycle: [
            { required: true, message: '请输入脉冲周期', trigger: 'blur' },
          ],
          PWM: [{ required: true, message: '请输入占空比', trigger: 'blur' }],
        },
        activeName: 'first',
        actionDays: [],
        searchDate: '',
        current: 0,
        page: 1,
        pages: 1,
        reverse: true,
        actions: [],
        loading: false,
        tabPosition: 'left',
        sliderValue: 0,
        rtuActionDisplays: [],
        states: {},
        autoRefresh: 0,
        intelval: null,
        searchForm: {
          timetran: '',
          namekey: '',
        },
        censusData: [],
        censusCount: '',
      }
    },
    computed: {
      ...mapGetters(['currentDevice', 'currentDeviceShow', 'rtk', 'user']),
      rtuPortDisplays() {
        return this.currentDevice.rtuPortDisplays || []
      },
      actionListener() {
        const serialno = this.currentDevice.serialno
        const activeName = this.activeName
        return { serialno, activeName }
      },
    },
    watch: {
      currentDevice: {
        handler(newVal) {
          this.rtuActionDisplays = newVal.rtuActionDisplays
          this.rtuActionDisplays.map((val) => {
            if (typeof val.action_arr === 'string') {
              val.action_arr = JSON.parse(val.action_arr)
            }
          })
          this.states = newVal.states
          if (newVal.states && newVal.states.REG_HMI_PWM) {
            this.sliderValue = Number(newVal.states.REG_HMI_PWM)
          }
        },
        deep: true,
        immediate: true,
      },
      actionListener: {
        handler(newVal) {
          if (newVal.serialno && newVal.activeName === 'second') {
            this.getActionDays()
          }
        },
        immediate: true,
      },
      searchDate: {
        handler(newVal) {
          if (newVal) {
            this.actions = []
            this.getActions()
          }
        },
        immediate: true,
      },
      currentDeviceShow: {
        handler(newVal) {
          if (this.currentDevice.settings && this.currentDevice.settings.bddx) {
            if (!newVal) {
              this.resetActive()
              this.$refs.mqttContainer.destroyConnection()
            } else {
              this.$nextTick(() => {
                this.$refs.mqttContainer.createConnection()
              })
            }
          }
        },
        immediate: true,
      },
    },
    methods: {
      reset() {
        this.searchForm = {
          serialno: '',
          timetran: '',
          namekey: '',
        }
        this.censusCount = ''
        this.censusData = []
      },
      async search() {
        if (!this.searchForm.timetran) {
          this.$message.error('请选择时间区间')
          return
        }
        if (!this.searchForm.namekey) {
          this.$message.error('请选择属性名称')
          return
        }
        this.searchForm.serialno = this.currentDevice.serialno
        const { data } = await getAll(this.searchForm)
        this.censusData = data
        this.censusCount = sum(data.map((val) => val.val))
      },
      refresh() {
        this.actions = []
        this.getActions()
      },
      getSubmitData(currentAttrs, currentData) {
        const data = {}
        currentAttrs.forEach((item) => {
          data[item.namekey] = currentData[item.namekey]
        })
        return data
      },
      pwmValve() {
        this.$confirm('确定要进行此操作吗？', '操作确认', {
          type: 'warning',
        }).then(() => {
          sendPWM(this.formData).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              showClose: true,
            })
          })
        })
      },
      closeTag(index) {
        this.formData.valves.splice(index, 1)
      },
      changeActionType(val) {
        const map = {
          1: 100,
          0: 0,
          2: 60,
        }
        this.formData.cycle = 60
        this.formData.PWM = map[val]
      },
      openFkqModal() {
        const rtuActionDisplays = this.currentDevice.rtuActionDisplays.filter(
          (val) => {
            return val.action_arr[0].namekey.indexOf('SetPulse') > -1
          }
        )
        const valves = []
        rtuActionDisplays.forEach((val) => {
          const port = val.action_arr[0].namekey.replace('SetPulse_', '')
          valves.push({
            rtu_serialno: this.currentDevice.serialno,
            port: +port,
            name: val.name,
          })
        })
        this.formData.valves = valves
        this.dialogVisible = true
      },
      resetActive() {
        this.activeName = 'first'
        this.searchDate = ''
        this.actionDays = []
      },
      async getActionDays() {
        const { data } = await getActionDays(this.currentDevice.serialno)
        this.actionDays = data
        this.searchDate = this.actionDays[this.current]
      },
      async getActions() {
        this.loading = true
        const { data } = await getActions({
          serialno: this.currentDevice.serialno,
          time: this.searchDate,
          page: this.page,
          pageSize: 100,
        })
        this.loading = false
        this.convertData(data)
      },
      handleClick(e) {
        this.searchDate = e.label
      },
      getClass(action) {
        if (action.indexOf('开') > -1 || action.indexOf('启动') > -1) {
          return 'color-success'
        }
        if (action.indexOf('关') > -1 || action.indexOf('停止') > -1) {
          return 'color-danger'
        }
        return ''
      },
      convertData(data) {
        this.actions = this.actions.concat(data.data)
        this.page = data.current_page
        this.pages = data.last_page
      },
      sendCommand(item, pitem) {
        this.$confirm('确定要进行此操作吗？', '操作确认', {
          type: 'warning',
        }).then(() => {
          if (Array.isArray(item.namekey)) {
            item.namekey.forEach((val) => {
              const data = {
                namekey: val,
                params: item.params,
              }
              this._sendCommand(data, pitem)
            })
          } else {
            const data = {
              namekey: item.namekey,
              value: item.params,
            }
            if (item.group) {
              data.group = item.group
            }
            this._sendCommand(data, pitem)
          }
        })
      },
      async _sendCommand(data, item) {
        const serialno = item.rtu_serialno || this.currentDevice.serialno
        const res = await sendCommand(data, serialno)
        if (res.errorCode === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            showClose: true,
          })
        }
      },
      changeSlider(item) {
        if (item.action_type === 'raw') {
          const sliderValue = Number(item.default_val)
          this.$confirm(
            `确定要将${item.name}设置为 ${sliderValue}% 吗？`,
            '操作确认',
            { type: 'info' }
          ).then(() => {
            const data = {
              namekey: item.action_arr[0].namekey,
              value: sliderValue,
            }
            this._sendCommand(data, item)
          })
        } else {
          const sliderValue = Number(this.sliderValue)
          this.$confirm(
            `确定要将行进速率设置为 ${sliderValue}% 吗？`,
            '操作确认',
            { type: 'info' }
          ).then(() => {
            const data = {
              namekey: item.action_arr[0].namekey,
              value: 256 + sliderValue,
            }
            this._sendCommand(data, item)
          })
        }
      },
      getButtonType(item, cindex) {
        if (item.show_state && item.mode !== 'raw') {
          const state_arr = JSON.parse(item.state_arr)
          let state = {}
          if (typeof state_arr.namekey === 'string') {
            state = +this.currentDevice.states[state_arr.namekey]
          } else {
            state = +this.currentDevice.states[state_arr.namekey[cindex]]
          }

          return state_arr.state[cindex] && state === +state_arr.state[cindex]
            ? 'primary'
            : 'default'
        }
        return 'default'
      },
    },
  }
</script>

<style lang="scss" scoped>
  .action-board {
    b {
      display: inline-block;
      width: 100px;
      text-align: right;
    }
  }
</style>
